package com.dzl.util;

import java.util.Arrays;
import java.util.BitSet;
import java.util.HashSet;
import java.util.Set;

/*******
 * 布隆过滤器，过滤重复数据
 * @author liuguanjun
 * @date 2021.09.08 14.13
 */
public class BloomFilter {

    //你的布隆过滤器容量 2的17次方
    private static final int DEFAULT_SIZE = 2 << 16;
    //bit数组，用来存放结果
    private static BitSet bitSet = new BitSet(DEFAULT_SIZE);
    //后面hash函数会用到，用来生成不同的hash值，可随意设置，别问我为什么这么多8，图个吉利
    private static final int[] ints = {1, 6, 16, 38, 58, 68};

    //add方法，计算出key的hash值，并将对应下标置为true
    public void add(Object key) {
        Arrays.stream(ints).forEach(i -> bitSet.set(hash(key, i)));
    }

    //判断key是否存在，true不一定说明key存在，但是false一定说明不存在
    public boolean isContain(Object key) {
        boolean result = true;
        for (int i : ints) {
            //短路与，只要有一个bit位为false，则返回false
            result = result && bitSet.get(hash(key, i));
        }
        return result;
    }

    //hash函数，借鉴了hashmap的扰动算法
    private int hash(Object key, int i) {
        int h;
        return key == null ? 0 : (i * (DEFAULT_SIZE - 1) & ((h = key.hashCode()) ^ (h >>> 16)));
    }


    public static void main(String[] args) {
        /*BloomFilter myNewBloomFilter = new BloomFilter();
        for (int i=0;i<100000;i++){
            myNewBloomFilter.add(i+"_张学友_18062754512");
        }
        myNewBloomFilter.add("15_张学友_18062754512");
        myNewBloomFilter.add("15_刘德华_18062754512");
        myNewBloomFilter.add("15_陈龙_18062754512");
        myNewBloomFilter.add("16_曹布草_18062754512");
        myNewBloomFilter.add("16_张学友_18062754512");
        myNewBloomFilter.add("17_张学友_18062754512");
        myNewBloomFilter.add("20_张学友3_18062754512");
        myNewBloomFilter.add("20_张学友4_18062754512");
        myNewBloomFilter.add("20_张学友5_18062754512");
        myNewBloomFilter.add("20_张学友6_18062754512");
        myNewBloomFilter.add("17_张学友2_18062754512");
        myNewBloomFilter.add("18_张学友1_18062754512");
        myNewBloomFilter.add("20_张学友1_18062754512");
        System.out.println(myNewBloomFilter.isContain("15_张学友_18062754512"));//true
        System.out.println(myNewBloomFilter.isContain("99999_张学友_18062754512"));//true
        System.out.println(myNewBloomFilter.isContain("100000_张学友_18062754512"));//false
        System.out.println(myNewBloomFilter.isContain("16_张学友_18062754512 "));//false
        System.out.println(myNewBloomFilter.isContain("16_张学友"));//false
        System.out.println(myNewBloomFilter.isContain("15_陈龙_18062754512"));//true*/

        /*String str = "test-welfare-saas.dingzhilian.com";
        System.out.println(str.split(".")[0]);*/
       /* int a = 100;
        int count1 = a / 100;
        int count2 = a % 100;
        System.out.println(count1);
        System.out.println(count2);*/
       String a = "aa-saas";
       System.out.println(a.replaceAll("-saas",""));
    }
}
